package com.headStorm.fileUtil;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.MultiFileResource;
import cn.hutool.core.lang.func.VoidFunc;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.socket.SocketUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyFileUtil {

    public static void main(String[] args) {
        System.out.println(StrUtil.toSymbolCase("User", '-'));
        List<File> files = new ArrayList<>();
        files.add(new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0284.jpg"));
//        files.add(new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0285.jpg"));
//        files.add(new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0286.jpg"));

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("files", new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0284.jpg"));

//        String body = HttpUtil.createPost("http://localhost:8883/api/test/testFileUpload")
//                .execute()
//                .body();
//        Map<String,Object> params = new HashMap<>();
//        params.put("name","task01");
//        testSwap(files,params);
        //testHutoolUtil();
        List<String> readLines = FileUtil.readLines(new File("C:\\Users\\86134\\Desktop\\newTaskFile.txt"), "utf-8");
        for (String line : readLines) {
            System.out.println(line.trim());
        }
    }

    /**
     * 用java模拟POST请求实现文件的上传。
     * @param map
     * @throws Exception
     */
    public static void uploadFile(List<File> files, Map<String, Object> map)  {

        String requestUrl = "http://localhost:8883/api/test/testFileUpload";
        // 换行符
        final String newLine = System.lineSeparator();
        final String boundaryPrefix = "--";
        try {
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST请求方法
            conn.setRequestMethod("POST");
            // conn.addRequestProperty("Authorization","JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsInVzZXJuYW1lIjoiZ2F0YyIsImV4cCI6MTYwNTg4MDcwNH0.LZJVh4KFbW6zsZ6T3AUit94NfkdpTlh0nBZ3LRW8j14");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream outputStream = conn.getOutputStream();
            DataOutputStream out = new DataOutputStream(outputStream);

            //传递参数
            if (map != null) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    stringBuilder.append(boundaryPrefix)
                            .append(BOUNDARY)
                            .append(newLine)
                            .append("Content-Disposition: form-data; name=\"")
                            .append(entry.getKey())
                            .append("\"").append(newLine).append(newLine)
                            .append(String.valueOf(entry.getValue()))
                            .append(newLine);
                }
                out.write(stringBuilder.toString().getBytes(Charset.forName("UTF-8")));
            }

            for (File file : files) {
                // 上传文件
                //   File file = new File(filePrefix + name);
                StringBuilder sb = new StringBuilder();
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data;name=\"files\";filename=\"").append(file.getName())
                        .append("\"").append(newLine);
                sb.append("Content-Type:application/octet-stream");
                sb.append(newLine);
                sb.append(newLine);
                out.write(sb.toString().getBytes());

                try (
                        DataInputStream in = new DataInputStream(new FileInputStream(file));
                ) {
                    byte[] bufferOut = new byte[1024];
                    int bytes = 0;
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    out.write(newLine.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();



            //定义BufferedReader输入流来读取URL的响应
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testSwap(List<File> files, Map<String, Object> map){

        String requestUrl = "http://192.168.126.129:8000/api/projects/12/tasks/";
        // 换行符
        final String newLine = System.lineSeparator();
        final String boundaryPrefix = "--";
        try {
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST请求方法
            conn.setRequestMethod("POST");
             conn.addRequestProperty("Authorization","JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsInVzZXJuYW1lIjoiZ2F0YyIsImV4cCI6MTYwNTk3MjU1NX0.ITxpzIGyxiW_3TeYC46fW1jvt5K_1p59hWzTShQ3yXI");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            OutputStream outputStream = conn.getOutputStream();
            DataOutputStream out = new DataOutputStream(outputStream);

            //传递参数
            if (map != null) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    stringBuilder.append(boundaryPrefix)
                            .append(BOUNDARY)
                            .append(newLine)
                            .append("Content-Disposition: form-data; name=\"")
                            .append(entry.getKey())
                            .append("\"").append(newLine).append(newLine)
                            .append(String.valueOf(entry.getValue()))
                            .append(newLine);
                }
                out.write(stringBuilder.toString().getBytes(Charset.forName("UTF-8")));
            }

            for (File file : files) {
                // 上传文件
                //   File file = new File(filePrefix + name);
                StringBuilder sb = new StringBuilder();
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data;name=\"files\";filename=\"").append(file.getName())
                        .append("\"").append(newLine);
                sb.append("Content-Type:application/octet-stream");
                sb.append(newLine);
                sb.append(newLine);
                out.write(sb.toString().getBytes());

                try (
                        DataInputStream in = new DataInputStream(new FileInputStream(file));
                ) {
                    byte[] bufferOut = new byte[1024];
                    int bytes = 0;
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    out.write(newLine.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();


            //定义BufferedReader输入流来读取URL的响应
            InputStream inputStream = null;
            inputStream = (conn.getResponseCode() < HttpStatus.HTTP_BAD_REQUEST) ? conn.getInputStream() : conn.getErrorStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testHutoolUtil(){

        List<File> files = new ArrayList<>();
        files.add(new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0284.jpg"));
        files.add(new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0285.jpg"));
        files.add(new File("D:\\BaiduNetdiskDownload\\测绘\\三维1\\DJI_0286.jpg"));


        MultiFileResource multiFileResource = new MultiFileResource(files);

        String body = HttpUtil.createPost("http://localhost:8883/api/test/testFileUpload")
                .form("files",multiFileResource)
                .execute()
                .body();
        System.out.println(body);

    }

}
